class SongsController < ApplicationController
  def index
    @artist = Artist.find(params[:artist_id])
    @songs = @artist.songs
  end

  def show
    @artist = Artist.find(params[:artist_id])
    @song = @artist.songs.find(params[:id])
  end

  def new
    @artist = Artist.find(params[:artist_id])
    @song = @artist.songs.build
  end

  def edit
    @artist = Artist.find(params[:artist_id])
    @song = @artist.songs.find(params[:id])
  end

  def create
    @artist = Artist.find(params[:artist_id])

    songtitle = params[:song][:title]

    success = false;
    songother = @artist.songs.to_ary.find { |s| s.title == songtitle}
    if songother == nil
      success = true
    end

    @song = @artist.songs.build(params[:song])

    if !success
      respond_to do |format|
        @song.errors.add('' , 'Song with such name already exists.')
        format.html { render :action => "new" }
      end
    end

    if success
      if @song.save
        redirect_to artist_song_url(@artist, @song)
      else
        render :action => "new"
      end
    end
  end

  def update
    @artist = Artist.find(params[:artist_id])
    @song = Song.find(params[:id])

    songtitle = params[:song][:title]
    songlyrics = params[:song][:lyrics]
    success = false;

    if @song.title == songtitle
      success = true
    end

    if !success
      songother = @artist.songs.to_ary.find { |s| s.title == songtitle}
      if songother == nil
        success = true
      end
    end

    if !success
      @song.title = songtitle
      @song.lyrics = songlyrics
      respond_to do |format|
        @song.errors.add('' , 'Song with such name already exists.')
        format.html { render :action => "edit" }
      end
    end

    if success
      if @song.update_attributes(params[:song])
        redirect_to artist_song_url(@artist, @song)
      else
        render :action => "edit"
      end
    end

  end

  def destroy
    @artist = Artist.find(params[:artist_id])
    @song = Song.find(params[:id])
    @song.destroy

    respond_to do |format|
      format.html { redirect_to artist_path(@artist) }
    end
  end

end
